package com.lhj.xxsc.cart.controller;

import com.lhj.xxsc.cart.feign.ProductFeignService;
import com.lhj.xxsc.cart.interceptor.CartInterceptor;
import com.lhj.xxsc.cart.service.CartService;
import com.lhj.xxsc.cart.to.UserInfoTo;
import com.lhj.xxsc.cart.vo.CartItemVo;
import com.lhj.xxsc.cart.vo.CartVo;
import org.bouncycastle.math.raw.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @author 罗惠江
 * @version 1.0
 * @email 1511619294@qq.com
 * @date 2020/12/30 14:14
 */
@Controller
public class CartController {

	@Autowired
	CartService cartService;

	/**
	 * cookie
	 * user - key 表示临时用户id
	 * 第一次使用购物车，会创建一个user—key
	 * 登录了session 里有
	 * 没登录 cookie 里的来
	 *
	 * @return
	 */
	@GetMapping("/cart.html")
	public String cartListPage(Model model) throws ExecutionException, InterruptedException {
		CartVo cart = cartService.getCart();
		model.addAttribute("cart", cart);
		return "cartList";
	}

	/**
	 * 添加商品到购物车
	 *
	 * @return
	 */
	@GetMapping("addToCart")
	public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes ra) throws ExecutionException, InterruptedException {
		cartService.addToCart(skuId, num);
		ra.addAttribute("skuId", skuId);
		return "redirect:http://cart.xxsc.com/addToCartSuccess.html";
	}

	@GetMapping("/addToCartSuccess.html")
	public String addTocartSuccess(@RequestParam("skuId") Long skuId, Model model) {
		CartItemVo cartItemVo = cartService.getCartItem(skuId);
		model.addAttribute("item", cartItemVo);
		return "success";
	}

	/**
	 * 修改购物车中购物的商品数量
	 *
	 * @param skuId
	 * @param check
	 * @return
	 */
	@GetMapping("checkItem")
	public String checkItem(@RequestParam("skuId") Long skuId, @RequestParam("check") Integer check) {
		cartService.checkItem(skuId, check);
		return "redirect:http://cart.xxsc.com/cart.html";
	}

	/**
	 * 修改购物车中商品的购物数量
	 *
	 * @param skuId
	 * @param num
	 * @return
	 */
	@GetMapping("countItem")
	public String countItem(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num) {
		cartService.changeItemCount(skuId, num);
		return "redirect:http://cart.xxsc.com/cart.html";
	}

	/**
	 * 删除购物车中改的某个商品
	 *
	 * @param skuId
	 * @return
	 */
	@GetMapping("deleteItem")
	public String deleteItem(@RequestParam("skuId") Long skuId) {
		cartService.deleteItem(skuId);
		return "redirect:http://cart.xxsc.com/cart.html";
	}

	/**
	 * 获取登录用户选中的购物项
	 *
	 * @return
	 */
	@GetMapping("/currentUsercartItems")
	@ResponseBody
	public List<CartItemVo> getCurrentUsercartItems() {

		return cartService.getUserCartItems();
	}
}
